<?php
declare(strict_types=1);
namespace app\common\business;

use app\common\model\mysql\Category as CategoryModel;
use think\Exception;

class Category extends BusiBase
{
    public function __construct()
    {
        $this->model = new CategoryModel();
    }

    /**
     * 添加分类
     *
     * @param array $data
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(array $data)
    {
        // 检查当前分类名称是否存在
        $find = $this->model->getDataByName($data['name']);
        if ($find['id'] && $find['pid'] == $data['pid']) throw new Exception('当前分类名已存在');

        // 添加当前分类
        $insertId = $this->insert($data);
        return $insertId;
    }

    /**
     * 获取正常使用分类信息
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalCate($field = true)
    {
        try{
            // 获取正常使用分类数据
            $cate  = $this->model->getNormalCategory($field);
        } catch (\Exception $e) {
            $this->errorLog("find Normal category error: ".$e->getMessage());
            return [];
        }
        // 判断分类数据是否为空
        if (!$cate) $cate = [];
        return $cate->toArray();
    }

    /**
     * 获取分类分页数据
     *
     * @param array $data
     * @param int $number
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getLists(array $data)
    {
        // 获取当前分类分页数据
        $res = $this->model->getLists($data);
        // 判断当前页数据是否为空
        if (!$res) return $this->returnNullDataArray();
        $result = $res->toArray();
        // 获取当前所有数据 ID
        $pidArr = array_column($result, 'id');
        if ($pidArr) {
            // 获取当前所有数据对应子分类个数
            $childCount = $this->model->getChildCountByPid($pidArr);
        } else {
            $childCount = [];
        }
        $childCount = array_column($childCount, 'count', 'pid');
        foreach ($result as $key=>$val) {
            $result[$key]['childCount'] = $childCount[$val['id']] ?? 0;
        }

        return $result;
    }

    /**
     * 获取当前分类的所有子集分类
     *
     * @param int $pid
     * @param string $field
     * @return array
     */
    public function getNormalByPid(int $pid = 0, string $field = "id,name,pid")
    {
        try{
            $res = $this->model->getNormalByPid($pid, $field);
        } catch (\Exception $e) {
            $this->errorLog("Category pid=$pid data find error: ".$e->getMessage());
            return [];
        }
        $data = $res->toArray();
        return $data;
    }

    /**
     * 根据 ID 修改对应分类数据
     *
     * @param int $id
     * @param array $update
     * @return bool
     * @throws Exception
     */
    public function updateCategoryById(int $id, array $update)
    {
        // 查找当前分类名是否存在
        $find = $this->model->getDataByName($update['name']);
        if ($find['id'] && $find['id'] != $id) throw new Exception('该分类名已存在');

        // 获取当前 ID 对应数据
        $data = $this->getById($id);
        // 判断该数据是否存在
        if (!$data) throw new Exception('该数据不存在');

        $res = $this->edit($id, $update);
        return $res;
    }

    /**
     * 获取当前分类上级分类
     *
     * @param int $categoryId
     * @param array $data
     * @return array
     */
    public function searchSubCategoryByCategoryId(int $categoryId, array $data = [])
    {
        // 查找当前分类信息
        $find = $this->getById($categoryId, 'id, name, pid');
        if ($find['pid'] > 0) {
            $data = $this->searchSubCategoryByCategoryId(intval($find['pid']), $data);
        }
        if (empty($data)) {
            $data['name'] = $find['name'];
        } else {
            $data['focus_ids'][] = $categoryId;
        }
        $supCategory = $this->getNormalByPid($categoryId, 'id, name');
        if ($supCategory) $data['list'][] = $supCategory;
        return $data;
    }

    /**
     * 获取当前分类下级分类
     *
     * @param int $categoryId
     * @param array $data
     * @return array
     */
    public function searchSupCategoryByCategoryId(int $categoryId, array $data = [])
    {
        $result = $this->getNormalByPid($categoryId);
        if (empty($result)) return $data;
        // $data['focus_ids'][] = $result[0]['id'];
        $data['list'][] = $result;
        $data = $this->searchSupCategoryByCategoryId($result[0]['id'], $data);
        return $data;
    }

    /**
     * 根据当前分类获取上下级完全分类
     *
     * @param int $categoryId
     * @param array $data
     * @return array
     */
    public function searchCategoryByCategoryId(int $categoryId, array $data = [])
    {
        // 获取当前分类上级分类信息
        $data = $this->searchSubCategoryByCategoryId($categoryId);
        // 获取当前默认下级信息
        $next = end($data['list'])[0];
        // 判断当前默认分类是否存在
        if (!isset($data['focus_ids'])) $data['focus_ids'] = [$next['id']];
        // 获取当前分类下级分类信息
        $data = $this->searchSupCategoryByCategoryId(intval($next['id']), $data);
        return $data;
    }
}